<?php

namespace app\admin\controller;

use think\exception\FuncNotFoundException;
use think\exception\ValidateException;
use app\model\UsersSessions;
use app\model\Users;

class Base extends \app\BaseController
{

	protected $userInfo = [];
	protected $sid = '';
	protected $ocid = '';
	protected $console = '';

	protected function initialize()
	{
		$controller = $this->request->controller();
		$action = $this->request->action();
		$app = app('http')->getName();

		$url =  "{$app}/{$controller}/{$action}";

		if (!in_array($url, config('my.nocheck'))) {
			$this->checkTokenAuth();
		}
	}

	//设置token
	protected function setToken($data)
	{

		$weid =	$data['weid'];
		$data =	serialize($data);
		$token = md5(uniqid());

		//登录的时候把token写入数据表
		$tokenInfo = UsersSessions::where('token', $token)->find();
		if (empty($tokenInfo)) {
			UsersSessions::create([
				'weid' => $weid,
				'token' => $token,
				'ptype' => 'pc',
				'ip' => getRealIP(),
				'expire_time' => time(),
				'data' => $data,
				'status' => 1
			]);
        } else {
            UsersSessions::where('token', $token)->update([
                'weid' => $weid,
                'token' => $token,
                'ptype' => 'pc',
                'ip' => getRealIP(),
                'expire_time' => time(),
                'data' => $data,
                'status' => 1
            ]);
        }

		return $token;
	}
	//设置token
	protected function getToken()
	{
		global $_W;
		$Authorization = $this->request->header('Authorization');
		$tokenarr = explode('|', $Authorization);
		$token = $tokenarr[0];

		if (is_array($tokenarr)) {
			foreach ($tokenarr as $vo) {
				$tmp = explode('=', $vo);
				if (is_array($tmp)) {
					$arr[$tmp[0]] = $tmp[1];
				}
			}
		}
		$this->sid =  $arr['sid'];
		$this->ocid =  $arr['ocid'];
		$this->console =  $arr['console'];
		
		if (!empty($arr['i'])) {
			$_W['i'] = $arr['i'];
			if (!empty($this->userInfo['id'])) {
				Users::where('id', $this->userInfo['id'])->update(['lastweid' => $arr['i']]);
			}
		}
		return $token;
	}

	//检测token
	protected function checkTokenAuth()
	{
		global $_W;
		$token = $this->getToken();
		if (!$token) {
			abort(101, 'token不能为空');
		}

		$tokenInfo = UsersSessions::where('token', $token)->find();

		if (empty($tokenInfo)) {
			abort(101, 'token不存在');
		} else {
			$tokenInfo = $tokenInfo->toArray();
		}

		if (!$tokenInfo['status']) {
			abort(101, '状态被禁用');
		}

		if (!$tokenInfo['dev_status']) {
			abort(101, '你已下线,账户在其它设备登录!');
		}

		if (($tokenInfo['expire_time'] - config('my.token_expire_time')) > time()) {
			abort(101, '登录状态已过期，请重新登录');
		}

		$this->userInfo = iunserializer($tokenInfo['data']);
		if (!empty($this->userInfo['sid'])) {
			$this->sid = $this->userInfo['sid'];
		}
		if (!empty($this->userInfo['ocid'])) {
			$this->ocid = $this->userInfo['ocid'];
		}
		
		$_W['uniacid'] = $this->userInfo['lastweid'];

		if($this->console==1){
			$_W['uniacid'] = 0;
		}

		event('DoLog', $this->userInfo['username']); //写入操作日志
	}

	//获取所有菜单
	protected function getTotalMenus()
	{
		$menu =  $this->getBaseMenus();
		$order_array = array_column($menu, 'sort');	 //数组排序
		array_multisort($order_array, SORT_ASC, $menu);

		return $menu;
	}

	//返回当前应用的菜单列表
	protected function getBaseMenus()
	{
		$field = 'id,pid,title,status,icon,sort,path,component_path';
		$query = \app\model\AdminMenu::field($field)->where(['status' => 1, 'type' => 1]);
		if (!empty($this->sid)) {
			$query->where('is_store', 1);
		} elseif (!empty($this->ocid)) {
			$query->where('is_city', 1);
		}elseif ($this->console == 1) {
			$query->where('is_console', 1);
		} else {
			$query->where('is_admin', 1);
		}

		if (config('my.app_name') == config('my.app_v2')) {
			$query->where('is_v2', 1);
		}

		if (config('my.app_name') == config('my.app_v3')) {
			$query->where('is_v3', 1);
		}

		$list = $query->order('sort asc')->select()->toArray();
		if ($list) {
			foreach ($list as $key => $val) {
				$menus[$key]['name'] = $val['path'];
				$menus[$key]['pid'] = $val['pid'];
				$menus[$key]['id'] = $val['id'];
				$menus[$key]['title'] = $val['title'];
				$menus[$key]['sort'] = $val['sort'];
				$menus[$key]['icon'] = $val['icon'] ? $val['icon'] : 'el-icon-menu';
				$menus[$key]['path'] = $val['path'];
				$menus[$key]['component_path'] = $val['component_path'];
			}
			return _generateListTree($menus, 0, ['id', 'pid']);
		}
	}

	//获取要加载的组件
	protected function getComponents($menu)
	{
		$components = [];
		foreach ($menu as $v) {
			$components[] = [
				'name' => $v['name'],
				'path' => $v['path'],
				'meta' => ['title' => $v['title']],
				'component_path' => $v['component_path']
			];
			if ($v['children']) {
				$components = array_merge($components, $this->getComponents($v['children']));
			}
		}
		return $components;
	}


	public function __call($method, $args)
	{
		throw new FuncNotFoundException('方法不存在', $method);
	}
}
